﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using XPMVC.Database;

namespace XPMVC
{
    public partial class Catalogue : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            xpEntities db = new xpEntities();

            var auction = db.Auction.Where(x => x.start_date < DateTime.Now && DateTime.Now < x.end_date);

            catalogueTable.Visible = auction.Count() > 0;

            if (catalogueTable.Visible)
            {
                auctionStart.Text = auction.FirstOrDefault().start_date.ToShortDateString();
                auctionEnd.Text = auction.FirstOrDefault().end_date.ToShortDateString();
            }
            else
            {
                auctionError.Visible = auction.Count() == 0;
                auctionError.InnerText = "There is no auction available";
            }

            if (Session["id"] == null)
            {
                catalogueTable.Visible = false;

                auctionError.Visible = true;
                auctionError.InnerText = "You have to log in to see the catalog";
            }

            if (!Page.IsPostBack)
            {
                {
                    var list = new List<Object>();

                    foreach (var art in db.ArtPiece.Where(x => x.available).ToList())
                    {
                        var cb = db.Bidding.Where(x => x.art_piece == art.id).OrderByDescending(x => x.id).FirstOrDefault();
                        int bid = cb == null ? 0 : cb.current_bid;

                        list.Add(new
                        {
                            picture = art.picture,
                            current_bid = bid,
                            name = art.name,
                            description = art.description,
                            author = art.author,
                            id = art.id,
                            location = art.location
                        });
                    }

                    catalogue.DataSource = list.ToList();
                    catalogue.DataBind();
                }
            }

            db.Dispose();
        }

        protected void btnBid_Click(object sender, EventArgs e)
        {

        }
    }
}